package com.example.doctor.service.impl;

import com.example.common.entity.*;
import com.example.common.utils.IdUtils;
import com.example.doctor.dto.req.*;
import com.example.doctor.dto.resp.*;
import com.example.doctor.jpa.*;
import com.example.doctor.mapper.TempleteMapper;
import com.example.doctor.service.TempleteService;
import com.example.doctor.utils.UserUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author sifan
 * @PackagName:com.example.doctor.service.impl
 * @ClassName: TempleteServiceImpl
 * @Description:
 * @date:2021/1/22 15:10
 */
@Service
public class TempleteServiceImpl implements TempleteService {


    @Resource
    TempleteMapper templeteMapper;

    @Resource
    TemplateRepository templateRepository;

    @Resource
    UserUtils userUtils;

    @Resource
    XDrugTempleteRepository xDrugTempleteRepository;

    @Resource
    KeysRepository keysRepository;

    @Resource
    TemplateDrugRepository templateDrugRepository;

    @Resource
    XDrugTempleteDrugRepository xDrugTempleteDrugRepository;

    @Override
    public Map<String, Object> List(TempleteListReq templeteListReq) {
        Map<String,Object>result=new HashMap<>();
        List<TempleteListRsp> list = new ArrayList<>();
        long count=0;
        if ("1".equals(templeteListReq.getTType())) {
            //中药
            List<Map<String, Object>> templateList = templeteMapper.selectZTemplate(userUtils.getUser().getDcId());
            if(templeteListReq.getTempType() != null && templeteListReq.getTempType() != 0) {
                count = templateList.stream().filter(m -> m.get("ttype").toString().equals(templeteListReq.getTempType().toString())).count();
                templateList = templateList.stream().filter(m -> m.get("ttype").toString().equals(templeteListReq.getTempType().toString())).
                        skip((templeteListReq.getPage()-1)*templeteListReq.getLimit()).
                        limit(templeteListReq.getLimit()).
                        collect(Collectors.toList());
            }else {
                count = templateList.stream().count();
                templateList = templateList.stream().
                        skip((templeteListReq.getPage()-1)*templeteListReq.getLimit()).
                        limit(templeteListReq.getLimit()).
                        collect(Collectors.toList());
            }
            for (Map<String, Object> template : templateList) {
                long tid = Long.valueOf(template.get("tid_bigint").toString());
                long ttype = Long.valueOf(template.get("ttype").toString());
                List<TDrug> tDrugs = null;
                if(ttype == 1)
                    tDrugs = templeteMapper.queryByTid(tid);
                else if(ttype == 2)
                    tDrugs = templeteMapper.queryByTidx(tid);
                TempleteListRsp templeteListRsp = new TempleteListRsp();
                templeteListRsp.setTName(template.get("t_name_nvarchar").toString());
                templeteListRsp.setTID(tid);
                templeteListRsp.setTType(ttype);
                templeteListRsp.setTDrug(tDrugs);
                list.add(templeteListRsp);
            }
            result.put("total",count);
            result.put("list",list);
        } else if ("2".equals(templeteListReq.getTType())) {
            //西药
            count =xDrugTempleteRepository.countByDcIdAndDType(userUtils.getUser().getDcId(),2);
            List<XDrugTemplete> xDrugTempleteList = xDrugTempleteRepository.findByDCid(userUtils.getUser().getDcId(), 2,(templeteListReq.getPage()-1)* templeteListReq.getLimit(),templeteListReq.getLimit());
            for (XDrugTemplete xDrugTemplete : xDrugTempleteList) {
                List<TDrug> tDrugs = templeteMapper.queryByTidx(xDrugTemplete.getTId());
                TempleteListRsp templeteListRsp = new TempleteListRsp();
                templeteListRsp.setTName(xDrugTemplete.getTName());
                templeteListRsp.setTID(xDrugTemplete.getTId());
                templeteListRsp.setTDrug(tDrugs);
                list.add(templeteListRsp);
            }
            result.put("total",count);
            result.put("list",list);
        }
        return result;
    }

    @Override
    public HashMap<String, Object> SelectZKeys() {
        List<String> Avoid = keysRepository.findByTypes(1);
        List<String> MedWay = keysRepository.findByTypes(2);
        List<String> UseTime = keysRepository.findByTypes(3);
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("Avoid", Avoid);
        hashMap.put("MedWay", MedWay);
        hashMap.put("UseTime", UseTime);
        return hashMap;
    }

    @Override
    public List<SearchZDrugRsp> SearchZDrug(SearchZDrugReq searchZDrugReq) {
        List<SearchZDrugRsp> searchZDrugRspList = templeteMapper.SearchZDrug(searchZDrugReq);
        return searchZDrugRspList;
    }

    @Override
    public HashMap<String, Object> SaveZTemplete(SaveZTempleteReq saveZTempleteReq) {

        Template templateDb = templateRepository.findById(saveZTempleteReq.getTemp().getTID()).orElse(null);
        SaveZTempleteTmp tmp = saveZTempleteReq.getTemp();
        List<SaveZTempleteDrugs> drugs = saveZTempleteReq.getDrugs();
        if (ObjectUtils.isEmpty(templateDb)) {
            Template template = new Template();
            Long Tid = IdUtils.generateId();
            template.setTId(Tid);
            template.setAvoid(tmp.getAvoid());
            template.setBaseDoes(tmp.getBaseDoes());
            template.setDayCount(tmp.getDayCount());
            template.setDoes(tmp.getDoes());
            template.setMedWay(tmp.getMedWay());
            template.setTName(tmp.getTName());
            template.setUseTime(tmp.getUseTime());
            template.setCreateTime(new Date());
            template.setDCid(userUtils.getUser().getDcId());
            templateRepository.save(template);
            for (SaveZTempleteDrugs drug : drugs) {
                TemplateDrug templateDrug = new TemplateDrug();
                templateDrug.setId(IdUtils.generateId());
                templateDrug.setTId(Tid);
                templateDrug.setDrugID(drug.getDrugID());
                templateDrug.setGuild(drug.getGuild());
                templateDrug.setNum(drug.getNum());
                templateDrugRepository.save(templateDrug);
            }
        } else {
            templateDb.setAvoid(tmp.getAvoid());
            templateDb.setBaseDoes(tmp.getBaseDoes());
            templateDb.setDayCount(tmp.getDayCount());
            templateDb.setDoes(tmp.getDoes());
            templateDb.setMedWay(tmp.getMedWay());
            templateDb.setTName(tmp.getTName());
            templateDb.setUseTime(tmp.getUseTime());
            templateRepository.save(templateDb);
            //删除药品信息
            templateDrugRepository.deleteBytId(templateDb.getTId());
            for (SaveZTempleteDrugs drug : drugs) {
                TemplateDrug templateDrug = new TemplateDrug();
                templateDrug.setId(IdUtils.generateId());
                templateDrug.setTId(templateDb.getTId());
                templateDrug.setDrugID(drug.getDrugID());
                templateDrug.setGuild(drug.getGuild());
                templateDrug.setNum(drug.getNum());
                templateDrugRepository.save(templateDrug);
            }
        }
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("Save", true);
        return hashMap;
    }

    @Override
    public ZInfoRsp ZInfo(ZInfoReq zInfoReq) {
        Template templateDb = templateRepository.findById(zInfoReq.getTID()).orElse(null);
        List<ZInfoDrugRsp> zInfoDrugRspList = templeteMapper.ZInfo(templateDb.getTId());
        ZInfoRsp zInfoRsp = new ZInfoRsp();
        zInfoRsp.setCook(templateDb.getCook());
        zInfoRsp.setAvoid(templateDb.getAvoid());
        zInfoRsp.setBaseDoes(templateDb.getBaseDoes());
        zInfoRsp.setDayCount(templateDb.getDayCount());
        zInfoRsp.setDoes(templateDb.getDoes());
        zInfoRsp.setSuggest(templateDb.getSuggest());
        zInfoRsp.setTName(templateDb.getTName());
        zInfoRsp.setTID(templateDb.getTId());
        zInfoRsp.setMedWay(templateDb.getMedWay());
        zInfoRsp.setUseTime(templateDb.getUseTime());
        zInfoRsp.setTDrug(zInfoDrugRspList);
        return zInfoRsp;
    }

    @Override
    public HashMap<String, Object> DelZTemplete(DelZTempleteReq delZTempleteReq) {
        templateRepository.deleteBytId(delZTempleteReq.getTID());
        templateDrugRepository.deleteBytId(delZTempleteReq.getTID());
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("Save", true);
        return hashMap;
    }

    @Override
    public HashMap<String, Object> SelectXKeys() {
        List<String> MedWay = keysRepository.findByTypes(2);
        List<String> Freq = keysRepository.findByTypes(4);
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("MedWay", MedWay);
        hashMap.put("Freq", Freq);
        return hashMap;
    }

    @Override
    public List<SearchXDiseaseRsp> SearchXDisease(SearchXDiseaseReq searchXDiseaseReq) {
        List<SearchXDiseaseRsp> searchXDiseaseRspList = templeteMapper.SearchXDisease(searchXDiseaseReq);
        return searchXDiseaseRspList;
    }

    @Override
    public List<SearchXDrugRsp> SearchXDrug(SearchXDrugReq searchXDrugReq) {
        List<SearchXDrugRsp> searchXDrugRspList = templeteMapper.SearchXDrug(searchXDrugReq);
        return searchXDrugRspList;
    }

    @Override
    public HashMap<String, Object> SaveXTemplete(SaveXTempleteReq saveXTempleteReq) {
        XDrugTemplete xDrugTempleteDb = xDrugTempleteRepository.findById(saveXTempleteReq.getTemp().getTID()).orElse(null);
        if (ObjectUtils.isEmpty(xDrugTempleteDb)) {
            SaveXTempleteTemp saveXTempleteTemp = saveXTempleteReq.getTemp();
            XDrugTemplete xDrugTemplete = new XDrugTemplete();
            Long tId = IdUtils.generateId();
            xDrugTemplete.setCreateTime(new Date());
            xDrugTemplete.setDcId(userUtils.getUser().getDcId());
            xDrugTemplete.setTId(tId);
            xDrugTemplete.setDisId(saveXTempleteTemp.getDisID());
            xDrugTemplete.setTName(saveXTempleteTemp.getTName());
            xDrugTemplete.setDType(saveXTempleteTemp.getType());
            xDrugTempleteRepository.save(xDrugTemplete);

            //保存药品
            List<SaveXTempleteDrugs> drugs = saveXTempleteReq.getDrugs();
            for (SaveXTempleteDrugs drug : drugs) {
                XDrugTempleteDrug xDrugTempleteDrug = new XDrugTempleteDrug();
                xDrugTempleteDrug.setTId(tId);
                xDrugTempleteDrug.setDrugId(drug.getDrugID());
                xDrugTempleteDrug.setDay(drug.getDay());
                xDrugTempleteDrug.setDoes(drug.getDoes());
                xDrugTempleteDrug.setFreq(drug.getFreq());
                xDrugTempleteDrug.setId(IdUtils.generateId());
                xDrugTempleteDrug.setRemark(drug.getRemark());
                xDrugTempleteDrug.setNum(drug.getNum());
                xDrugTempleteDrug.setMedWay(drug.getMedWay());
                xDrugTempleteDrugRepository.save(xDrugTempleteDrug);
            }
        } else {
            SaveXTempleteTemp saveXTempleteTemp = saveXTempleteReq.getTemp();
            xDrugTempleteDb.setDisId(saveXTempleteTemp.getDisID());
            xDrugTempleteDb.setTName(saveXTempleteTemp.getTName());
            xDrugTempleteRepository.save(xDrugTempleteDb);

            //删除药品信息
            xDrugTempleteDrugRepository.deleteByTiD(xDrugTempleteDb.getTId());
            //保存药品
            List<SaveXTempleteDrugs> drugs = saveXTempleteReq.getDrugs();
            for (SaveXTempleteDrugs drug : drugs) {
                XDrugTempleteDrug xDrugTempleteDrug = new XDrugTempleteDrug();
                xDrugTempleteDrug.setTId(saveXTempleteTemp.getTID());
                xDrugTempleteDrug.setDrugId(drug.getDrugID());
                xDrugTempleteDrug.setDay(drug.getDay());
                xDrugTempleteDrug.setDoes(drug.getDoes());
                xDrugTempleteDrug.setFreq(drug.getFreq());
                xDrugTempleteDrug.setId(IdUtils.generateId());
                xDrugTempleteDrug.setRemark(drug.getRemark());
                xDrugTempleteDrug.setNum(drug.getNum());
                xDrugTempleteDrug.setMedWay(drug.getMedWay());
                xDrugTempleteDrugRepository.save(xDrugTempleteDrug);
            }
        }
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("Save", true);
        return hashMap;
    }

    @Override
    public XInfoRsp XInfo(XInfoReq xInfoReq) {
      XDrugTemplete xDrugTemplete = xDrugTempleteRepository.findById(xInfoReq.getTID()).orElse(null);
        List<TDrugx> tDrugxes = templeteMapper.XInfo(xDrugTemplete.getTId());
        XInfoRsp xInfoRsp = new XInfoRsp();
        xInfoRsp.setTID(xDrugTemplete.getTId());
        xInfoRsp.setTName(xDrugTemplete.getTName());
        xInfoRsp.setDisID(xDrugTemplete.getDisId());
        xInfoRsp.setDisID2(xDrugTemplete.getDisId2());
        xInfoRsp.setTDrug(tDrugxes);
        return xInfoRsp;
    }

    @Override
    public HashMap<String, Object> DelXTemplete(DelXTempleteReq delXTempleteReq) {
        xDrugTempleteRepository.deleteById(delXTempleteReq.getTID());
        xDrugTempleteDrugRepository.deleteByTiD(delXTempleteReq.getTID());
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("Save", true);
        return hashMap;
    }
}
